package top.lshaci.learning.rule;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;

import java.math.BigDecimal;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * RuleService
 *
 * @author lshaci
 * @since 1.0.0
 */
public class RuleService<R, P, T> {
    Map<T, BaseRule> ruleMap;

    {
        ruleMap = ClassUtil.scanPackage("top.lshaci.learning.springboot.web.service", cls -> {
            if (cls.isInterface() || ClassUtil.isAbstract(cls)) {
                return false;
            }
            return BaseRule.class.isAssignableFrom(cls);
        }).stream()
                .map(cls -> (BaseRule) ReflectUtil.newInstance(cls))
                .collect(Collectors.toMap(rule -> (T) rule.type(), Function.identity()));
    }

    public R exec(T type, P param) {
        BaseRule rule = ruleMap.get(type);
        if (rule == null) {
            return null;
        }
        System.err.println("Rule: " + rule);
        return (R) rule.exec(param);
    }

    public static void main(String[] args) {
        RuleService<BigDecimal, RuleDto, Integer> ruleService = new RuleService<>();
        RuleDto dto = new RuleDto();
        dto.setAmount(new BigDecimal("30"));
        BigDecimal result = ruleService.exec(1, dto);
        System.err.println("result: " + result);
    }
}
